//
//  XLPersonPageViewController.m
//  XiangLove
//
//  Created by 陈宪栋 on 2017/12/18.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "XLPersonPageViewController.h"
#import "XLPersonPageNavBarView.h"
#import "XLPersonPageUserInfoView.h"
#import "XLPPCollectionViewCell.h"
#import "XLPPGuardianListView.h"
#import "XLPPHeaderView.h"
#import "XLPPFooterView.h"
#import "BMHPickerView.h"
#import "BMHCommentIssueView.h"

#import "XLGuardianListViewController.h"
#import "IMAChatViewController.h"
#import "CallMakeViewController.h"

#import "XLPPUserInfoModel.h"
#import "XLPPCamgirlVideoModel.h"
#import "XLPPGuardianModel.h"
#import "HomeCallModel.h"

#import "XLHTTPSessionManager+Camgirl.h"
#import <AFHTTPSessionManager.h>


#import <MJRefresh.h>
#import <UtilsMacro.h>
#import <ReactiveCocoa.h>
#import <IQKeyboardManager.h>
#import "UIImage+Gradient.h"
#import <NSString+NSHash.h>
#import <ImSDK/TIMFriendshipManager.h>
#import "VideoRecordViewController.h"
#import "XLHTTPSessionManager+Analytics.h"
#import "TopUpViewController.h"
#import "XLHTTPSessionManager+matchOrder.h"
#import "XLOrderViewController.h"
#import "XLNewOrderViewController.h"


////////
#import "XLPersonCenterTool.h"
#import "XLPersonCenterScrollView.h"
#import "XLPersonCenterHeader.h"
#import "XLPersonCenterProxyViewController.h"

#import "XLDataViewController.h"
#import "XLVideoViewController.h"

#import "XLUserInfoDetailModel.h"

#import "XLReprotUserVC.h"
//编辑资料界面
#import "XLCommitDataController.h"
#import "XLMakeVoiceChatVC.h"

#import "XLRecordTool.h"
// 387 + 44
#define kHeaderHeight   433

@interface XLPersonPageViewController ()<XLPPGuardianListViewDelegate, CustomerDelegate, BMHPickerViewDelegate,UIScrollViewDelegate,UIPageViewControllerDelegate,UIPageViewControllerDataSource,VideoVcDelegate>
@property (nonatomic, strong) XLPersonPageNavBarView       *navBarView;
@property (nonatomic, strong) XLPersonPageUserInfoView     *userInfoView;

//@property (nonatomic, strong) XLPPHeaderView               *headerView;
//@property (nonatomic, strong) UICollectionView             *collectionView;
@property (nonatomic, strong) UIButton
*  collectionButton;
@property (nonatomic, strong) UIButton                     *messageButton;
@property (nonatomic, strong) UIButton                     *videoChatButton;

//和他语音聊天
@property (nonatomic, strong) UIButton                     *voiceChatButton;
@property (nonatomic, strong) UIButton                     *uploadButton;

@property (nonatomic, strong) CustomerAVPlayerView         *customerView;

@property (nonatomic, strong) XLPPUserInfoModel            *userInfoModel;
@property (nonatomic, strong) NSArray                      *guardianDataArray;
@property (nonatomic, strong) NSArray                      *dataArray;
@property (nonatomic, assign) BOOL                          userInfoIsLoading;
@property (nonatomic, assign) BOOL                          guardianIsLoading;
@property (nonatomic, assign) BOOL                          videoListIsLoading;
@property (nonatomic, assign) BOOL                          guardianIsEmpty;
@property (nonatomic, assign) BOOL                          videoListIsEmpty;
@property (nonatomic, assign) BOOL                          statusBarIsDefault;
@property (nonatomic, assign) BOOL                          isInBlack;
@property (nonatomic, assign) BOOL                          isSelf;

@property (nonatomic, strong) UIView                        *beautyTopView;
@property (nonatomic, strong) UIImageView                   *videochatTopImg;
@property (nonatomic, strong) UILabel                       *redPoint;
@property (nonatomic, strong) NSMutableArray                *orderListAry;
@property (nonatomic, assign) NSInteger                      orderInter;
@property (nonatomic, assign) BOOL                           isAppear;




//获取数据
@property (nonatomic, strong) XLUserInfoDetailModel *  userDetailModel;


//背景容器
@property (nonatomic, strong) XLPersonCenterScrollView *  baseScroll;

//区头显示
@property (nonatomic, strong) XLPersonCenterHeader *  headeView;

//用于切换要选择的控制器
@property (nonatomic, strong) UIPageViewController *  pageController;

//分段选择所对应的控制器数组
@property (nonatomic, strong) NSArray<XLPersonCenterProxyViewController *> *  controllers;

//选择对应控制器 (个人信息)
@property (nonatomic, strong) XLDataViewController *  dataViewController;

//选择对应控制器 （视频列表）
@property (nonatomic, strong) XLVideoViewController *  videoController;

//是否可以滚动视图
@property (nonatomic, assign) BOOL isContentScroll;


@end

@implementation XLPersonPageViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.isAppear = YES;
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        //[self userOderListData];
    }
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
    manager.shouldResignOnTouchOutside = NO;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.shouldShowToolbarPlaceholder = NO;
    manager.enableAutoToolbar = NO;
    [self reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.shouldShowToolbarPlaceholder = YES;
    manager.enableAutoToolbar = YES;
    self.isAppear = NO;
    
    if ([[XLRecordTool shareRecordTool].player isPlaying]) {
        [[XLRecordTool shareRecordTool].player stop];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.isSelf = [self.userId isEqualToString:[[XLAccountManager shareInstance] model].Id];
    
    if (self.isSelf == YES){
        [self getAppconfigList];
        
    }
    
    //辅助变量初始化
    [self initToolSource];
    
    //绘制UI显示
    [self setCustomeView];
    
    //请求数据
    [self requestSource];
    
//    [self setupView];
    [self setupData];
    [self bindingData];
    //[self addObserver];
    [self analyticsEvent1];
    
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        //[self StartGrabSingle];
    }
    
    
}

#pragma mark    - - - 请求数据 - - -
- (void)requestSource
{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/PersonalHomepage/GetPersonalHomepageInfo" parameters:@{@"userId":self.userId} resultClass:[XLUserInfoDetailModel class]] subscribeNext:^(id x) {
        [MBProgressHUD hideHUDForView:self.view];
        
        self.userDetailModel = x;
        
        self.headeView.userInfoModel = x;
        
        self.dataViewController.userInfoModel = x;
        self.videoController.userInfoModel = x;
        
        if (self.userDetailModel.IsAnchor) {
            
            self.controllers = @[
                                 self.videoController,
                                 self.dataViewController
                                 ];
            self.headeView.segmentView.titles = @[@"视频",@"资料"];
            
            //更新下方语音按钮和视频按钮
            [self updateVoiceAndVideo];
            
        }else{
            self.controllers = @[
                                 self.dataViewController,
                                 self.videoController
                                 ];
            self.headeView.segmentView.titles = @[@"资料",@"视频"];
        }
        
        
        //设置默认显示
        [self setCurrentWillShowController:0];
        
        NSLog(@"requestSource");
//        [self setBottomActionButton];
        
    } error:^(NSError *error) {
        
        self.controllers = @[
                             self.dataViewController,
                             self.videoController
                             ];
        self.headeView.segmentView.titles = @[@"资料",@"视频"];
        
        //设置默认显示
        [self setCurrentWillShowController:0];
        
        NSLog(@"requestSource");
//        [self setBottomActionButton];
        
    }];
}


#pragma mark    - - - 其他数据初始化 - - -

/**
 辅助变量初始化
 */
- (void)initToolSource
{
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didScrollViewWithNotification:) name:personCenterProxyScrollNotification object:nil];
    //刷新结束
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerRefreshEnd:) name:personCenterProxyHeaderRefresh object:nil];
    
    //内容视图是否可以滚动
    self.isContentScroll = YES;
    
    
}

#pragma mark    - - - 绘制UI显示 - - -

/**
 绘制主要界面显示
 */
- (void)setCustomeView
{
    //设置主要背景容器
    [self setBackgroundScroll];
    
    //设置头部显示
    [self setHeaderView];
    
    //设置子控制器
    [self setPageViewController];
    
    //
    [self setupView];
    
    [self setBottomActionButton];
}

/**
 设置主要背景容器
 */
- (void)setBackgroundScroll
{
    self.baseScroll = [[XLPersonCenterScrollView alloc] init];
    self.baseScroll.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:_baseScroll];
    
    //修饰
    self.baseScroll.showsVerticalScrollIndicator = NO;
    self.baseScroll.showsHorizontalScrollIndicator = NO;
    self.baseScroll.delegate = self;
    self.baseScroll.bounces = NO;

    [self.baseScroll.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
    
    if (@available(iOS 11.0, *)) {
        self.baseScroll.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //约束
    [self.baseScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    
//    [self.baseScroll.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
//    [self.baseScroll.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor constant:-103].active = YES;
//    [self.baseScroll.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
//    [self.baseScroll.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;
//    [self.baseScroll.widthAnchor constraintEqualToAnchor:self.view.widthAnchor].active = YES;
//    [self.baseScroll.heightAnchor constraintEqualToConstant:self.view.bounds.size.height-103].active = YES;
}

/**
 设置头部显示
 */
- (void)setHeaderView
{
    self.headeView = [[XLPersonCenterHeader alloc] init];
    self.headeView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.baseScroll addSubview:self.headeView];
    
    __weak typeof(self)weakSelf = self;
    //修饰
    [self.headeView.segmentView setDidClickButtonHandler:^(UIButton *button, NSInteger index) {
        
        NSLog(@"点击的按钮");
        [weakSelf setCurrentWillShowController:index];
        
    }];
    //关注点击事件
    self.headeView.followClickBlock = ^{
        //发送关注信息
        [[[XLHTTPSessionManager sharedManager] XLV2POST:@"/api/v2/UserInfo/Follow" parameters:@{@"FollowId":weakSelf.userId,@"FansId":[XLAccountManager shareInstance].model.Id} resultClass:nil] subscribeNext:^(id x) {
            weakSelf.headeView.attentionBt.hidden = YES;
            NSLog(@"关注成功%@",x);
            
            
        } error:^(NSError *error) {
            
            NSLog(@"关注失败%@",error);
            
        }];
    };
    
    //设置分页选择显示
    if (self.userDetailModel.IsAnchor) {
        self.headeView.segmentView.titles = @[@"视频",@"资料"];
    }else{
        self.headeView.segmentView.titles = @[@"资料",@"视频"];
    }
    
    //约束
    
    [self.headeView.topAnchor constraintEqualToAnchor:self.baseScroll.topAnchor].active = YES;
    [self.headeView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
    [self.headeView.widthAnchor constraintEqualToAnchor:self.view.widthAnchor].active = YES;
    [self.headeView.heightAnchor constraintEqualToConstant:433].active = YES;
    
}

/**
 切换控制器
 */
- (void)setPageViewController
{
    self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:(UIPageViewControllerTransitionStyleScroll) navigationOrientation:(UIPageViewControllerNavigationOrientationHorizontal) options:@{UIPageViewControllerOptionInterPageSpacingKey:@(10.0)}];
    
    //修饰
    self.pageController.delegate = self;
    self.pageController.dataSource = self;
    self.pageController.view.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self addChildViewController:self.pageController];
    [self.baseScroll addSubview:self.pageController.view];
    
    CGFloat naviBarHeight = IS_IPhoneX ? 88.0 : 64.0;
    
    CGFloat pageHeight = 44 + naviBarHeight;
    
    //约束 387 44+64+48
    [self.pageController.view.topAnchor constraintEqualToAnchor:self.headeView.bottomAnchor].active = YES;
    [self.pageController.view.widthAnchor constraintEqualToAnchor:self.view.widthAnchor].active = YES;
    [self.pageController.view.heightAnchor constraintEqualToAnchor:self.view.heightAnchor constant:-pageHeight].active = YES;
    [self.pageController.view.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
    [self.pageController.view.bottomAnchor constraintEqualToAnchor:self.baseScroll.bottomAnchor constant:0].active = YES;
    
    [self.pageController didMoveToParentViewController:self];
    
}

#pragma mark    - - - Method - - -
/**
 设置当前需要显示的视图
 */
- (void)setCurrentWillShowController:(NSInteger)index
{
    //是否设置错误
    if (index > self.controllers.count) {
        return;
    }
    
    //查找当前控制器
    XLPersonCenterProxyViewController *proxyController = (XLPersonCenterProxyViewController *)self.pageController.childViewControllers.lastObject;
    
    //获取当前控制器所在位置
    NSInteger currentIndex = [self.controllers indexOfObject:proxyController];
    
    //获取需要显示的控制器
    UIViewController *willShowVc = [self.controllers objectAtIndex:index];
    
    //设置获取方向
    UIPageViewControllerNavigationDirection direction = (currentIndex > index) ? UIPageViewControllerNavigationDirectionReverse : UIPageViewControllerNavigationDirectionForward;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //设置显示控制器
        [self.pageController setViewControllers:@[willShowVc] direction:direction animated:NO completion:^(BOOL finished) {
            
        }];
        
    });
    
}


#pragma mark    - - - UIScrollViewDelegate - - -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView == self.baseScroll) {
        //获取导航栏高度 用来计算活动空间
        
        CGFloat navigationBarHeight = IS_IPhoneX ? 88 : 64;
        
        CGFloat segmentHeight = self.headeView.segmentView.frame.size.height;
        
        //活动空间：导航栏高度：被遮盖部分，分段选择高度：露出紧贴导航部分
        CGFloat activityHeight = kHeaderHeight - navigationBarHeight - segmentHeight;
        
        if (scrollView.contentOffset.y >= activityHeight) {
            
            //设置滑动位置
            [scrollView setContentOffset:CGPointMake(0, activityHeight)];
            
            self.isContentScroll = NO;
            
            //设置滚动视图
            for (XLPersonCenterProxyViewController *proxyVc in self.controllers) {
                proxyVc.contentIsScroll = YES;
            }
        }else{
            
            if (!self.isContentScroll) {
                [scrollView setContentOffset:CGPointMake(0, activityHeight)];
            }
        }
    }
    
    CGFloat alpha1 = scrollView.contentOffset.y / 100 > 1 ? 1 : scrollView.contentOffset.y / 100;
    self.navBarView.backgroundColor = RGBA(255, 255, 255, alpha1);
    //
    self.navBarView.backButton1.alpha = 1-alpha1;
    self.navBarView.moreButton1.alpha = 1;
    self.navBarView.moreButton2.alpha = 1;
    self.navBarView.backButton2.alpha = alpha1;
    self.navBarView.titleLabel.alpha = alpha1;
    self.navBarView.titleLabel.textColor=RGBA(0, 0, 0, alpha1);
    
    self.navBarView.backButton2.imageView.tintColor = RGBA(0, 0, 0, alpha1);
    self.navBarView.moreButton1.imageView.tintColor = RGBA(0, 0, 0, alpha1);
    if (alpha1<0.1) {
        self.navBarView.moreButton1.imageView.tintColor = RGBA(255, 255, 255, 1);
    }
    
    self.navBarView.layer.shadowColor = RGBA(0, 0, 0, alpha1).CGColor;
    
    
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    for (XLPersonCenterProxyViewController *Vc in self.controllers) {
        
        [Vc scrollViewToTop];
        
    }
    
    return YES;
}


#pragma mark    - - - UIPageViewControllerDelegate DataSource - - -

/**
 返回当前页面的下一个控制器
 */
- (nullable UIViewController *)pageViewController:(nonnull UIPageViewController *)pageViewController viewControllerAfterViewController:(nonnull UIViewController *)viewController {
    
    NSInteger index = [self.controllers indexOfObject:(XLPersonCenterProxyViewController *)viewController];
    
    if (index < self.controllers.count - 1) {
        return [self.controllers objectAtIndex:index+1];
    }
    
    return nil;
    
}

/**
 返回当前页面的上一个控制器
 */
- (nullable UIViewController *)pageViewController:(nonnull UIPageViewController *)pageViewController viewControllerBeforeViewController:(nonnull UIViewController *)viewController {
    
    // 获取控制器位置
    NSInteger index = [self.controllers indexOfObject:(XLPersonCenterProxyViewController *)viewController];
    
    if (index == 0 || index == NSNotFound) {
        return nil;
    }
    
    return [self.controllers objectAtIndex:index-1];
}

/**
 切换控制器之后需要切换指示器的位置
 */
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed
{
    //根据获取的控制器对象找到下标位置
    XLPersonCenterProxyViewController *Vc = self.pageController.viewControllers.lastObject;
    
    NSInteger index = [self.controllers indexOfObject:Vc];
    
    if (index >= 0 && index != NSNotFound) {
        
        //设置指示器
        [self.headeView.segmentView setIndicatorLocationWithIndex:index];
    }
}

#pragma mark    - - - 消息通知 - - -
- (void)didScrollViewWithNotification:(NSNotification *)notifaction
{
    self.isContentScroll = YES;
    
    for (XLPersonCenterProxyViewController *Vc in self.controllers) {
        
        Vc.contentIsScroll = NO;
        
    }
    
}

- (void)headerRefreshEnd:(NSNotification *)notifaction
{
    if ([self.baseScroll.mj_header isRefreshing]) {
        [self.baseScroll.mj_header endRefreshing];
    }
}


- (void)headerNormalRefreshAction
{
    XLPersonCenterProxyViewController *proxyVc = (XLPersonCenterProxyViewController *)self.pageController.viewControllers.lastObject;
    
    [proxyVc beginHeaderRefresh];
}


#pragma mark    - - - 懒加载 - - -
//- (NSArray<XLPersonCenterProxyViewController *> *)controllers
//{
//    if (!_controllers) {
//
//
//        self.controllers = @[
//                             self.videoController,
//                             self.dataViewController
//                             ];
//
//    }
//
//
//
//    return _controllers;
//}

- (XLDataViewController *)dataViewController{
    
    if (!_dataViewController) {
        self.dataViewController = [[XLDataViewController alloc] init];
    }
    return _dataViewController;
}

- (XLVideoViewController *)videoController
{
    if (!_videoController) {
        self.videoController = [[XLVideoViewController alloc] init];
        self.videoController.videoDelegate = self;
        self.videoController.userId = self.userId;
    }
    return _videoController;
}


#pragma mark    -   -   - VideoController Delegate - - -

- (void)videoDidSelectActionWithIndexPath:(NSIndexPath *)indexPath
{
    [self analyticsEvent2];
}


- (void)addObserver {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"OrderRefresh" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
        {
            if (self.isAppear) {
                [self userOderListData];
            }
        }
    }];
}

#pragma mark -
#pragma mark - 开始抢单
-(void)StartGrabSingle
{
    _beautyTopView = [[UIView alloc] init];
    _beautyTopView.backgroundColor = kClearColor;
    [self.view addSubview:_beautyTopView];
    [self hostTapGestureRecognizer:_beautyTopView];
    [_beautyTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.bottom.equalTo(self.view.mas_bottom).offset(-70);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    
    _videochatTopImg = [[UIImageView alloc] init];
    _videochatTopImg.image = [UIImage imageNamed:@"home_but_qiang2_n"];
    [_beautyTopView addSubview:_videochatTopImg];
    [_videochatTopImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_beautyTopView);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    
    _redPoint = [[UILabel alloc] init];
    _redPoint.textColor = kWhiteColor;
    _redPoint.font = kSetFont(10);
    _redPoint.layer.masksToBounds = YES;
    _redPoint.layer.cornerRadius  = 8;
    _redPoint.backgroundColor = RGBA(248, 75, 90, 1);
    _redPoint.textAlignment = NSTextAlignmentCenter;
    [_videochatTopImg addSubview:_redPoint];
    
}

- (void)updateCellOnline
{
    NSInteger readCount = self.orderInter;
    if ( readCount <= 9 &&  readCount > 0)
    {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(20, 16));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }else if (readCount >= 10) {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 20));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }else {
        _redPoint.hidden = YES;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(0, 0));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }
    [_redPoint setText:readCount > 99 ? @"99+" : [NSString stringWithFormat:@"%ld",readCount]];
}

-(void)hostTapGestureRecognizer:(UIView *)view
{
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(hostTapAction:)];
    [view addGestureRecognizer:tap];
}

#pragma mark -
#pragma mark -主播-抢单大厅
-(void)hostTapAction:(UITapGestureRecognizer *)tap
{
    //主播-抢单大厅
    NSLog(@"主播-抢单大厅");
    if ([self checkCameraAuthorization]) {
        XLNewOrderViewController *vc = [[XLNewOrderViewController alloc] init];
        vc.view.backgroundColor=[UIColor colorWithWhite:0 alpha:0.77];
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:vc animated:YES completion:^(void){
            vc.view.superview.backgroundColor = [UIColor clearColor];
        }];
    }
}

-(void)userOderListData
{
    [[[XLHTTPSessionManager sharedManager] getOrderListWithAnchorId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        NSLog(@"订单列表数据==%@",x);
        self.orderListAry = x;
        if (self.orderListAry.count > 0 || self.orderListAry.count == 0) {
            self.orderInter = self.orderListAry.count;
            [self updateCellOnline];
        }
    } error:^(NSError *error) {
    }];
}

-(void)getAppconfigList
{
    [[[XLHTTPSessionManager sharedManager] getAppconfigLis] subscribeNext:^(id x) {
        
        NSLog(@"配置--%@",x);
        NSString * success = [NSString stringWithFormat:@"%@",x[@"success"]];
        NSString * CompressionLeve;
        NSString * VideoLeve;
        NSString * WeChatAppId;
        if (![x[@"data"]isKindOfClass:[NSNull class]]) {
            CompressionLeve = [NSString stringWithFormat:@"%@",x[@"data"][@"CompressionLeve"]];
            VideoLeve       = [NSString stringWithFormat:@"%@",x[@"data"][@"VideoLeve"]];
            WeChatAppId     = [NSString stringWithFormat:@"%@",x[@"data"][@"WeChatAppId"]];
        }
        
        if ([success isEqualToString:@"0"]) {
            [UserDefaults setObject:CompressionLeve forKey:CompressionLeveID];
            [UserDefaults setObject:VideoLeve       forKey:VideoLeveID];
            
            if ([WeChatAppId isEqualToString:@"wx278d848f035a09ca"]) {
                [UserDefaults setObject:@"wx278d848f035a09ca"     forKey:wxGlobAppID];
                [UserDefaults setObject:@"2a81af61b1a6bc2ccf3dc0e0cec03de3"             forKey:wxGlobSECRET];
                [UserDefaults setObject:@"HZBoYiBoXiuQuWeiXinZhiFu20161212"             forKey:wxGlobPrivate];
            }else{
                [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
                [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
                [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
                
            }
        }
        
        
    } error:^(NSError *error) {
        
        [UserDefaults setObject:@"wxa8f4e7a0fe25c966"     forKey:wxGlobAppID];
        [UserDefaults setObject:@"a280f90481b8d97fc8cb47d2a514303e"             forKey:wxGlobSECRET];
        [UserDefaults setObject:@"BaoMiHuaWangYDWeiXinZhiFu2016721"             forKey:wxGlobPrivate];
        
    }];
    
}


/// 添加单边阴影效果
- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    theView.layer.shadowColor = theColor.CGColor;
    theView.layer.shadowOffset = CGSizeMake(0,2);
    theView.layer.shadowOpacity = 0.5;
    theView.layer.shadowRadius = 2;
    // 单边阴影 顶边
    float shadowPathWidth = theView.layer.shadowRadius;
    CGRect shadowRect = CGRectMake(0, theView.bounds.size.height-3, theView.bounds.size.width, shadowPathWidth);
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:shadowRect];
    theView.layer.shadowPath = path.CGPath;
}

- (void)updateVoiceAndVideo
{
    if (self.isSelf == NO) {
        
        if (self.userDetailModel.IsAnchor) {
            self.videoChatButton.hidden = NO;
            [self.messageButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(65, 49));
            }];
            
            //视频聊天
            [_videoChatButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(89, 70));
                make.bottom.equalTo(self.view.mas_bottom).offset(-15);
                make.centerX.equalTo(self.view.mas_centerX);
            }];

            
            [_voiceChatButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(65, 49));
                make.right.equalTo(self.view.mas_right).offset(kRealWidthValue(-39));
                make.bottom.equalTo(self.view.mas_bottom).offset(-26);
            }];
        }else{
            self.videoChatButton.hidden = YES;
            [self.messageButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(kRealWidthValue(110), 49));
            }];
            [_videoChatButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(0, 48));
                make.right.equalTo(self.view.mas_right).offset(10);
                make.bottom.equalTo(self.view.mas_bottom);
            }];
            [_voiceChatButton mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(kRealWidthValue(110), 49));
                make.right.equalTo(self.view.mas_right).offset(-kRealWidthValue(43));
                make.bottom.equalTo(self.view.mas_bottom).offset(-26);
            }];
            
        }
        
    }
}

#pragma mark --- 底部按钮布局
- (void)setBottomActionButton
{
    if (self.isSelf == NO) {
        UIView *bgView = [[UIView alloc] init];
        [self.view addSubview:bgView];
        
        CAGradientLayer *gl = [CAGradientLayer layer];
        gl.frame = CGRectMake(0,0,kScreenW,103);
        gl.startPoint = CGPointMake(0.48, 0);
        gl.endPoint = CGPointMake(0.48, 1);
        gl.colors = @[(__bridge id)[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1].CGColor];
        gl.locations = @[@(0), @(1.0f)];
        [bgView.layer addSublayer:gl];
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(ScreenWidth, 103));
            make.left.equalTo(self.view.mas_left);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
        
        
        _messageButton = [[UIButton alloc] init];
        _messageButton.layer.backgroundColor = KWhiteColor.CGColor;
        _messageButton.layer.cornerRadius = 24.5;
        _messageButton.layer.shadowColor = RGBA(0, 0, 0, 0.1).CGColor;
        _messageButton.layer.shadowOffset = CGSizeMake(0,2);
        _messageButton.layer.shadowOpacity = 1;
        _messageButton.layer.shadowRadius = 4;
        [_messageButton setImage:[UIImage imageNamed:@"conten_icon_shape_n"] forState:UIControlStateNormal];
        [self.view addSubview:_messageButton];
        
        //语音按钮
        _voiceChatButton = [[UIButton alloc] init];
        _voiceChatButton.layer.backgroundColor = KWhiteColor.CGColor;
        _voiceChatButton.layer.cornerRadius = 24.5;
        _voiceChatButton.layer.shadowColor = RGBA(0, 0, 0, 0.1).CGColor;
        _voiceChatButton.layer.shadowOffset = CGSizeMake(0,2);
        _voiceChatButton.layer.shadowOpacity = 1;
        _voiceChatButton.layer.shadowRadius = 4;
        [_voiceChatButton setImage:[UIImage imageNamed:@"conten_icon_yuyin_n"] forState:UIControlStateNormal];
        [self.view addSubview:_voiceChatButton];
        
        _videoChatButton = [[UIButton alloc] init];
        CAGradientLayer *videoChatlayer = [CAGradientLayer layer];
        videoChatlayer.frame = CGRectMake(0,0,89,70);
        videoChatlayer.startPoint = CGPointMake(0.19, 0.73);
        videoChatlayer.endPoint = CGPointMake(1, 0.17);
        videoChatlayer.colors = @[(__bridge id)[UIColor colorWithRed:255/255.0 green:223/255.0 blue:2/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:187/255.0 blue:1/255.0 alpha:1].CGColor];
        videoChatlayer.locations = @[@(0), @(1.0f)];
        _videoChatButton.layer.cornerRadius = 35;
        _videoChatButton.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1].CGColor;
        _videoChatButton.layer.shadowOffset = CGSizeMake(0,2);
        _videoChatButton.layer.shadowOpacity = 1;
        _videoChatButton.layer.shadowRadius = 4;
        _videoChatButton.layer.masksToBounds = YES;
        [_videoChatButton setImage:IMAGE_NAMED(@"conten_icon_shiping_n") forState:UIControlStateNormal];
        [_videoChatButton.layer addSublayer:videoChatlayer];
        [_videoChatButton bringSubviewToFront:_videoChatButton.imageView];
        [self.view addSubview:_videoChatButton];
        
        
        
        
        //是否是主播，如果是，显示语音和视频两种聊天方式，用户只有语音聊天
        if (self.userDetailModel.IsAnchor) {
            _videoChatButton.hidden = NO;
            
            //视频聊天约束
            [_videoChatButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(89, 70));
                make.bottom.equalTo(self.view.mas_bottom).offset(-15);
                make.centerX.equalTo(self.view.mas_centerX);
            }];
            
            //私信约束
            [_messageButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(65, 49));
                make.left.equalTo(self.view.mas_left).offset(kRealWidthValue(39));
                make.bottom.equalTo(self.view.mas_bottom).offset(-26);
            }];
            
            [_voiceChatButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(65, 49));
                make.right.equalTo(self.view.mas_right).offset(kRealWidthValue(-39));
                make.bottom.equalTo(self.view.mas_bottom).offset(-26);
            }];
            
        }else{
            _videoChatButton.hidden = YES;
            //私信约束
            [_messageButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(kRealWidthValue(110), 49));
                make.left.equalTo(self.view.mas_left).offset(kRealWidthValue(43));
                make.bottom.equalTo(self.view.mas_bottom).offset(-26);
            }];
            //视频聊天约束
            [_voiceChatButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(kRealWidthValue(110), 49));
                make.right.equalTo(self.view.mas_right).offset(-kRealWidthValue(43));
                make.bottom.equalTo(self.view.mas_bottom).offset(-26);
            }];
        }
    }
}

//设置下方视频，聊天，关注按钮
- (void)setupView {
    _navBarView = [[XLPersonPageNavBarView alloc] initWithFrame:IS_IPhoneX ? CGRectMake(0, 0, ScreenWidth, 88) : CGRectMake(0, 0, ScreenWidth, 64)];
    _navBarView.moreButton1.hidden = self.isSelf;
    _navBarView.moreButton2.hidden = !self.isSelf;
    [self.view addSubview:_navBarView];
    
    //设置阴影
    [self addShadowToView:self.navBarView withColor:RGBA(0, 0, 0, 0)];
    
    if (self.isSelf == NO) {
        
    } else {
        
        _navBarView.moreButton2.hidden = self.isSelf;
        
        _uploadButton = [[UIButton alloc] init];
        _uploadButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_uploadButton setTitle:@"编辑资料" forState:UIControlStateNormal];
        [_uploadButton setImage:[UIImage imageNamed:@"common_icon_bianji_n"] forState:(UIControlStateNormal)];
        [_uploadButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 4)];
        [_uploadButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 4, 0, 0)];
        //            [_uploadButton setBackgroundImage:[UIImage gradientImageFromColors:@[RGB(255, 95, 109), RGB(255, 195, 113)] frame:CGRectMake(0, 0, ScreenWidth, 48)] forState:UIControlStateNormal];
        _uploadButton.backgroundColor = [UIColor colorWithRed:255/255.0 green:187/255.0 blue:1/255.0 alpha:1];
        [self.view addSubview:_uploadButton];
        [_uploadButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(ScreenWidth, 48));
            make.right.equalTo(self.view.mas_right);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
}

- (void)setupData {
    self.userInfoIsLoading = YES;
    self.guardianIsLoading = YES;
    self.videoListIsLoading = YES;
    self.dataArray = @[];
    self.guardianDataArray = @[];
    //    [self.collectionView reloadData];
    [self reloadData];
    //self.userId = @"470304";
    
}

//获取信息
- (void)reloadData {
    @weakify(self);
    XLHTTPSessionManager *manager = [XLHTTPSessionManager sharedManager];
    manager.cachePloy = XLHTTPCachePloy_Server;
    [[manager getCamgirlUserInfoWithUserId:self.userId] subscribeNext:^(id x) {
        @strongify(self);
        self.userInfoModel = x;
        self.navBarView.titleLabel.text = self.userInfoModel.NickName;
        self.userInfoIsLoading = NO;
        //        [self.collectionView reloadData];
    } error:^(NSError *error) {
        @strongify(self);
        self.userInfoIsLoading = NO;
        //        [self.collectionView reloadData];
    }];
    
    [[manager getUserGiveRankWithUserId:self.userId] subscribeNext:^(id x) {
        @strongify(self);
        self.guardianDataArray = x;
        self.guardianIsEmpty = self.guardianDataArray.count == 0;
        self.guardianIsLoading = NO;
        //        [self.collectionView reloadData];
    } error:^(NSError *error) {
        @strongify(self);
        self.guardianIsLoading = NO;
        self.guardianIsEmpty = YES;
        //        [self.collectionView reloadData];
    }];
    
    [[manager getCamgirlVideoListWithUserId:self.userId] subscribeNext:^(id x) {
        @strongify(self);
        self.dataArray = x;
        self.videoListIsLoading = NO;
        self.videoListIsEmpty = self.dataArray.count == 0;
        //        [self.collectionView reloadData];
    } error:^(NSError *error) {
        @strongify(self);
        self.videoListIsLoading = NO;
        self.videoListIsEmpty = YES;
        //        [self.collectionView reloadData];
    }];
    
    [self checkIsInBlack];
}

//绑定navigationBar事件
- (void)bindingData {
    [self.navBarView.backButton1 addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView.backButton2 addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navBarView.moreButton1 addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
   // [self.navBarView.moreButton2 addTarget:self action:@selector(EditAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //更新版本，关注更换位置
    //    [self.collectionButton addTarget:self action:@selector(followAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.messageButton addTarget:self action:@selector(messageAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.voiceChatButton addTarget:self action:@selector(voiceChatAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.videoChatButton addTarget:self action:@selector(videoChatAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.uploadButton addTarget:self action:@selector(uploadAction:) forControlEvents:UIControlEventTouchUpInside];
}

//是否拉入黑名单
- (void)checkIsInBlack {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://api.xiuquapp.com"]];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", @"text/json",nil];
    long long timeStamp = [[NSDate date] timeIntervalSince1970];
    NSString *sign = [[F(@"uname=%zd", timeStamp) MD5] uppercaseString];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.userId forKey:@"buserId"];
    [parameters setObject:@"3" forKey:@"type"];
    [parameters setObject:[[XLAccountManager shareInstance] model].Id forKey:@"userId"];
    [parameters setObject:@(timeStamp) forKey:@"timestamp"];
    [parameters setObject:sign forKey:@"sign"];
    
    @weakify(self);
    [manager POST:@"/MobileInterface/BlackList/GetBlacklist.ashx" parameters:parameters progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self);
        BMHLog(@"%@", responseObject);
        id resultObj = [responseObject objectForKey:@"result"];
        NSInteger errCode = [resultObj[@"errcode"] integerValue];
        if (errCode == 1) {
            self.isInBlack = YES;
        } else {
            self.isInBlack = NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        BMHLog(@"%@", error);
    }];
}


#pragma makr - XLPPGuardianListViewDelegate
- (void)guardianListView:(XLPPGuardianListView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    XLPPGuardianModel *model = self.guardianDataArray[indexPath.item];
    XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
    vc.userId = model.UserId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)guardianListViewSelected {
    XLGuardianListViewController *vc = [[XLGuardianListViewController alloc] init];
    vc.dataArray = self.guardianDataArray;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Action
- (void)videoPlayAction:(UIButton *)button {
    _customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:self.userInfoModel.VideoUrl isFileUrl:NO];
    _customerView.Delegate = self;
    
    [_customerView.player play];
    [_customerView.controlView setPlayButtonSelected:YES];
    [[UIApplication sharedApplication].keyWindow addSubview:_customerView];
}

- (void)backAction:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)moreAction:(UIButton *)button {
    NSArray *titleArray;
    if (self.isInBlack) {
        titleArray = @[@"举报"];
    } else {
        titleArray = @[@"举报"];
    }
    BMHPickerView *pickerView = [[BMHPickerView alloc] initWithTitleArray:titleArray delegate:self];
    [pickerView show];
}

- (void)messageAction:(UIButton *)button {
    [self analyticsEvent3];
    IMAChatViewController *chatvc = nil;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[IMAChatViewController class]]) {
            chatvc = (IMAChatViewController *)vc;
            break;
        }
    }
    if (chatvc) {
        [self.navigationController popToViewController:chatvc animated:YES];
    } else {
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[self.userId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    chat.isAnchor = self.userDetailModel.IsAnchor;
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
    }
}

//点击关注
- (void)followAction:(UIButton *)sender
{
    NSLog(@"点击关注");
    
    //更新约束
    [_collectionButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(0, 48));
        make.left.equalTo(self.view.mas_left).offset(ScreenWidth/8);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    //删除关注子视图
    [_messageButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(kRealWidthValue(110), 49));
        make.left.equalTo(self.view.mas_left).offset(kRealWidthValue(43));
        make.bottom.equalTo(self.view.mas_bottom).offset(-26);
    }];
    
    //动画过渡
    
    //发送关注信息
    [[[XLHTTPSessionManager sharedManager] XLV2POST:@"/api/v2/UserInfo/Follow" parameters:@{@"FollowId":self.userId,@"FansId":[XLAccountManager shareInstance].model.Id} resultClass:nil] subscribeNext:^(id x) {
        
        NSLog(@"关注成功%@",x);
        
        
    } error:^(NSError *error) {
        
        NSLog(@"关注失败%@",error);
        
    }];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.view layoutIfNeeded];
        
    } completion:^(BOOL finished) {
        
        //删除关注子视图
        [self.collectionButton removeFromSuperview];
        
    }];
}

#pragma mark ***************发起语音
- (void)VoiceChatWithModel:(HomeCallModel *)model2 {//v2版本
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/api/v2/VideoChat/Connect1V1VoiceChat" parameters:@{
                                                                                                         @"userId":[[XLAccountManager shareInstance] model].Id,
                                                                                                         @"anchorId":K_DEFULT(_userId),
                                                                                                         @"type":@"1"
                                                                                                         } resultClass:[HomeCallModel class]] subscribeNext:^(id x) {
        
        [MBProgressHUD hideHUDForView:self.view];
        HomeCallModel *model = x;
        XLMakeVoiceChatVC *make = [[XLMakeVoiceChatVC alloc] init];//拔打电话
        //        make.IsOneTimeCall = model.IsOneTimeCall;
        //        make.UserFreeSecond = model.UserFreeSecond;
        make.peerId = [NSString stringWithFormat:@"%@",model.AnchorId];
        make.headStr = self.userInfoModel.HeadImg;
        make.nickNameStr = self.userInfoModel.NickName;
        make.detailStr = [NSString stringWithFormat:@"%@ %@",model.HostCity,model.job];
        make.addressStr = model.HostCity;
        make.ageStr = model.Age;
        make.jobStr = model.job;
        make.ismic = YES;
        //        make.iscinema = YES;
        make.callid = model.CallId;
        make.videoid = model.CallId;
        make.moneyStr = @"20";
        make.gradeStr = [NSString stringWithFormat:@"%@",model.BGradeIcon];
        UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:make];
        [self presentViewController:nav animated:YES completion:nil];
        
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (error.code == 6) {  //余额不足
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
            TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
            topVC.In_purchase = isIn_purchase;
            [self.navigationController pushViewController:topVC animated:YES];
        } else {  //被拉入黑名单//对方已屏蔽视聊
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
        }
    }];
}

#pragma mark ***************检查是否可以语音
- (void)voiceChatAction:(UIButton *)button
{
    //检查是否可以通话
    [self setUserInfoAction];
    
    HomeCallModel *model = nil;
    if ([self checkCameraAuthorization]) {
        [self VoiceChatWithModel:model];
    }
}

#pragma mark ***************检查是否可以视频通话
- (void)videoChatAction:(UIButton *)button { //检查是否可以通话
    
    //设置视频前的准备信息
    [self setUserInfoAction];
    
    HomeCallModel *model = nil;
    if ([self checkCameraAuthorization]) {
        [self chatWithModel:model];
    }
}

//设置令牌信息
- (void)setUserInfoAction
{
    [self analyticsEvent4];
    NSString * useridStr = self.userId;
    NSDate * senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
}

//2018.08.07  sz 以后是编辑资料
- (void)uploadAction:(UIButton *)button {
    XLCommitDataController *commitDataVc = [[XLCommitDataController alloc] init];
    commitDataVc.userId = self.userId;
    commitDataVc.detailModel = self.userDetailModel;
    [self.navigationController pushViewController:commitDataVc animated:YES];
}
#pragma mark ***************发起视频
- (void)chatWithModel:(HomeCallModel *)model2 {//v2版本
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[[XLHTTPSessionManager sharedManager] makeCallWithAnchorId:_userId userId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        [MBProgressHUD hideHUDForView:self.view];
        HomeCallModel *model = x;
        CallMakeViewController *make = [[CallMakeViewController alloc] init];//拔打电话
        make.IsOneTimeCall = model.IsOneTimeCall;
        make.UserFreeSecond = model.UserCardSecond;
        make.peerId = [NSString stringWithFormat:@"%@",model.AnchorId];
        make.headStr = self.userInfoModel.HeadImg;
        make.nickNameStr = self.userInfoModel.NickName;
        make.detailStr = [NSString stringWithFormat:@"%@ %@",model.HostCity,model.job];
        make.addressStr = model.HostCity;
        make.ageStr = model.Age;
        make.jobStr = model.job;
        make.ismic = YES;
        make.iscinema = YES;
        make.callid = model.CallId;
        make.videoid = model.CallId;
        make.moneyStr = @"20";
        make.gradeStr = [NSString stringWithFormat:@"%@",model.BGradeIcon];
        UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:make];
        [self presentViewController:nav animated:YES completion:nil];
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (error.code == 6) {  //余额不足
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
            TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
            topVC.In_purchase = isIn_purchase;
            [self.navigationController pushViewController:topVC animated:YES];
        } else {  //被拉入黑名单//对方已屏蔽视聊
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
        }
    }];
}

#pragma mark - CustomerDelegate
- (void)clickBackBtnVideoPlay {
    [_customerView.player pause];
    [_customerView removeFromSuperview];
    _customerView = nil;
}

- (void)videoIsStartToPlay {
    
}

#pragma mark - BMHPickerViewDelegate
- (void)pickView:(BMHPickerView *)pickView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        
        XLReprotUserVC *vc = [[XLReprotUserVC alloc]init];
        vc.toUserId = self.userId;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (buttonIndex == 1) {
        if (self.isInBlack) {
            [self removeBlack];
        } else {
            [self addBlack];
        }
    }
}

- (void)addBlack {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://api.xiuquapp.com"]];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", @"text/json",nil];
    long long timeStamp = [[NSDate date] timeIntervalSince1970];
    NSString *sign = [[F(@"uname=%zd", timeStamp) MD5] uppercaseString];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.userId forKey:@"buserId"];
    [parameters setObject:@"1" forKey:@"type"];
    [parameters setObject:[[XLAccountManager shareInstance] model].Id forKey:@"userId"];
    [parameters setObject:@(timeStamp) forKey:@"timestamp"];
    [parameters setObject:sign forKey:@"sign"];
    @weakify(self);
    [manager POST:@"/MobileInterface/BlackList/GetBlacklist.ashx" parameters:parameters progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self);
        BMHLog(@"%@", responseObject);
        [HelpTool startTipViewWithText:@"拉黑成功" duration:2.0 type:kTipViewTypeNone];
//        [MBProgressHUD showContent:@"拉黑成功"];
        self.isInBlack = YES;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        BMHLog(@"%@", error);
    }];
}

- (void)removeBlack {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://api.xiuquapp.com"]];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", @"text/json",nil];
    long long timeStamp = [[NSDate date] timeIntervalSince1970];
    NSString *sign = [[F(@"uname=%zd", timeStamp) MD5] uppercaseString];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.userId forKey:@"buserId"];
    [parameters setObject:@"2" forKey:@"type"];
    [parameters setObject:[[XLAccountManager shareInstance] model].Id forKey:@"userId"];
    [parameters setObject:@(timeStamp) forKey:@"timestamp"];
    [parameters setObject:sign forKey:@"sign"];
    @weakify(self);
    [manager POST:@"/MobileInterface/BlackList/GetBlacklist.ashx" parameters:parameters progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self);
        BMHLog(@"%@", responseObject);
        [HelpTool startTipViewWithText:@"移出黑名单成功" duration:2.0 type:kTipViewTypeNone];
//        [MBProgressHUD showContent:@"移出黑名单成功"];
        self.isInBlack = NO;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        BMHLog(@"%@", error);
    }];
}

- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }
    
    if (!isAvalible) {
        [self analyticsEvent5];
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [self presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

#pragma mark - 统计
- (NSDictionary *)genrateAttributes {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    if ([[XLAccountManager shareInstance] model].Id) {
        [attributes setObject:[[XLAccountManager shareInstance] model].Id ?: @"" forKey:@"userid"];
    }
    if (self.userId) {
        [attributes setObject:self.userId ?: @"" forKey:@"camgirlid"];
    }
    return attributes.copy;
}

- (void)analyticsEvent1 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_myindex" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_myindex" action:@"xl_myindex" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent2 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_clickvideo" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_myindex" action:@"xl_clickvideo" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent3 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_clickmsgchat" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_myindex" action:@"xl_clickmsgchat" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent4 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_clickvideochat" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_myindex" action:@"xl_clickvideochat" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}
- (void)analyticsEvent5 {//拒绝拒绝开启摄像头权限
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_refusepurview" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_myindex" action:@"xl_refusepurview" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
